package com.ITArmy.service.impl;

import com.ITArmy.beans.Message;
import com.ITArmy.beans.Reply;
import com.ITArmy.beans.Shows.ReplyMessage;
import com.ITArmy.beans.User;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.dao.MessageMapper;
import com.ITArmy.dao.ReplyMapper;
import com.ITArmy.dao.UserMapper;
import com.ITArmy.service.ReplyService;
import com.ITArmy.util.CheckMessage;
import com.ITArmy.util.GetUserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    ReplyMapper replyMapper;
    @Autowired
    MessageMapper messageMapper;

    GetUserSession getUserSession = new GetUserSession();
    @Autowired
    UserMapper userMapper;

    //回复评论
    @Override
    public ServerResponse replyComment(HttpServletRequest request, Reply reply) {
        User user = getUserSession.getUser(request);
        reply.setrUId(user.getuId());
        reply.setrTime(new Date());
        int resultCount = replyMapper.insertSelective(reply);
        if (resultCount==1){
            Message message=new Message();
            message.setcHid(reply.getrId());
            message.setuId(user.getuId());
            message.setuCid(reply.getrUId());
            message.setTime(new Date());
            Reply r=replyMapper.findReplyByUidAndTime(user.getuId(),reply.getrTime());
            message.setcHid(r.getrId());
            messageMapper.insertSelective(message);
        }
        CheckMessage check=new CheckMessage();
        return check.getMessage(resultCount,"回复成功","回复失败");
    }

    //删除回复的评论
    @Override
    public ServerResponse deleteReply(long replyId) {
        int resultCount = replyMapper.deleteByPrimaryKey(replyId);
        CheckMessage check=new CheckMessage();
        return check.getMessage(resultCount,"删除成功","删除失败");
    }
    //根据评论的id获取所有的回复信息
    @Override
    public List<ReplyMessage> getReplyMessageByCid(long cId) {
        List<Reply> replies = replyMapper.selectAllReply(cId);
        List<ReplyMessage> replyMessages = new ArrayList<>();
        if (replies == null) {
            return replyMessages;
        }
        //进行封装所有有关回复的信息
        for (int i = 0; i < replies.size(); i++) {
            ReplyMessage replyMessage = new ReplyMessage();
            //回复的具体信息
            replyMessage.setReply(replies.get(i));
            //回复人的信息
            replyMessage.setUser(userMapper.selectByPrimaryKey(replies.get(i).getrUId()));
            //被回复人的信息
            replyMessage.setbUser(userMapper.selectByPrimaryKey(replies.get(i).gettUId()));
            replyMessages.add(replyMessage);
        }
        return replyMessages;
    }

}
